package com.smart.community.property.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.dto.RepairOrderWorkDTO;
import com.smart.community.property.service.IRepairOrderWorkService;
import com.smart.community.property.vo.RepairOrderWorkVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维修工单工作管理扩展控制器
 *
 * @author Wu.Liang
 * @since 2025-01-30
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/property/repair-work")
@RequiredArgsConstructor
@Validated
@Tag(name = "维修工单工作管理", description = "维修工单工作管理扩展功能接口")
public class RepairOrderWorkController {

    private final IRepairOrderWorkService repairOrderWorkService;

    @GetMapping("/page")
    @Operation(summary = "分页查询维修工单（工作管理扩展）", description = "分页查询维修工单列表")
    public ResponseEntity<IPage<RepairOrderWorkVO>> getRepairOrderWorkPage(
            @Parameter(description = "当前页", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "工单状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "维修类型") @RequestParam(required = false) Integer repairType,
            @Parameter(description = "优先级") @RequestParam(required = false) Integer priority,
            @Parameter(description = "紧急程度") @RequestParam(required = false) Integer urgencyLevel,
            @Parameter(description = "维修人员ID") @RequestParam(required = false) Long repairmanId,
            @Parameter(description = "查询开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "查询结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "工单标题") @RequestParam(required = false) String title) {
        
        log.info("分页查询维修工单（工作管理扩展），当前页：{}，每页大小：{}", current, size);
        
        Map<String, Object> params = new HashMap<>();
        params.put("status", status);
        params.put("repairType", repairType);
        params.put("priority", priority);
        params.put("urgencyLevel", urgencyLevel);
        params.put("repairmanId", repairmanId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("title", title);
        params.put("propertyCompanyId", SecurityUtils.getCurrentPropertyCompanyId());
        
        IPage<RepairOrderWorkVO> result = repairOrderWorkService.getRepairOrderWorkPage(current, size, params);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询维修工单详情（工作管理扩展）", description = "根据ID查询维修工单详情")
    public ResponseEntity<RepairOrderWorkVO> getRepairOrderWorkById(
            @Parameter(description = "维修工单ID", required = true) @PathVariable @NotNull Long id) {
        
        log.info("根据ID查询维修工单详情（工作管理扩展），ID：{}", id);
        
        RepairOrderWorkVO result = repairOrderWorkService.getRepairOrderWorkById(id);
        return ResponseEntity.ok(result);
    }

    @PostMapping
    @Operation(summary = "新增维修工单（工作管理扩展）", description = "新增维修工单")
    public ResponseEntity<Boolean> addRepairOrderWork(
            @Parameter(description = "维修工单DTO", required = true) @RequestBody @Valid RepairOrderWorkDTO repairOrderWorkDTO) {
        
        log.info("新增维修工单（工作管理扩展），标题：{}，维修类型：{}", 
                repairOrderWorkDTO.getTitle(), repairOrderWorkDTO.getRepairType());
        
        // 设置当前用户的物业公司ID
        repairOrderWorkDTO.setPropertyCompanyId(SecurityUtils.getCurrentPropertyCompanyId());
        
        boolean result = repairOrderWorkService.addRepairOrderWork(repairOrderWorkDTO);
        return ResponseEntity.ok(result);
    }

    @PutMapping
    @Operation(summary = "更新维修工单（工作管理扩展）", description = "更新维修工单")
    public ResponseEntity<Boolean> updateRepairOrderWork(
            @Parameter(description = "维修工单DTO", required = true) @RequestBody @Valid RepairOrderWorkDTO repairOrderWorkDTO) {
        
        log.info("更新维修工单（工作管理扩展），ID：{}，标题：{}", 
                repairOrderWorkDTO.getId(), repairOrderWorkDTO.getTitle());
        
        boolean result = repairOrderWorkService.updateRepairOrderWork(repairOrderWorkDTO);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/{orderId}/assign")
    @Operation(summary = "分配维修工单", description = "分配维修工单给维修人员")
    public ResponseEntity<Boolean> assignRepairOrder(
            @Parameter(description = "工单ID", required = true) @PathVariable @NotNull Long orderId,
            @Parameter(description = "维修人员ID", required = true) @RequestParam @NotNull Long repairmanId,
            @Parameter(description = "预计完成时间", required = true) @RequestParam @NotNull String estimatedCompleteTime,
            @Parameter(description = "分配备注") @RequestParam(required = false) String remark) {
        
        log.info("分配维修工单，工单ID：{}，维修人员ID：{}，预计完成时间：{}", orderId, repairmanId, estimatedCompleteTime);
        
        boolean result = repairOrderWorkService.assignRepairOrder(orderId, repairmanId, estimatedCompleteTime, remark);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/batch/assign")
    @Operation(summary = "批量分配维修工单", description = "批量分配维修工单给维修人员")
    public ResponseEntity<Map<String, Integer>> batchAssignRepairOrders(
            @Parameter(description = "工单ID列表", required = true) @RequestBody @NotEmpty List<Long> orderIds,
            @Parameter(description = "维修人员ID", required = true) @RequestParam @NotNull Long repairmanId,
            @Parameter(description = "预计完成时间", required = true) @RequestParam @NotNull String estimatedCompleteTime) {
        
        log.info("批量分配维修工单，工单IDs：{}，维修人员ID：{}，预计完成时间：{}", orderIds, repairmanId, estimatedCompleteTime);
        
        Map<String, Integer> result = repairOrderWorkService.batchAssignRepairOrders(orderIds, repairmanId, estimatedCompleteTime);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/{orderId}/start")
    @Operation(summary = "开始维修", description = "维修人员开始维修工单")
    public ResponseEntity<Boolean> startRepair(
            @Parameter(description = "工单ID", required = true) @PathVariable @NotNull Long orderId,
            @Parameter(description = "材料清单") @RequestParam(required = false) List<String> materialList,
            @Parameter(description = "开始维修备注") @RequestParam(required = false) String remark) {
        
        log.info("开始维修，工单ID：{}，材料清单：{}", orderId, materialList);
        
        boolean result = repairOrderWorkService.startRepair(orderId, materialList, remark);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/{orderId}/complete")
    @Operation(summary = "完成维修", description = "维修人员完成维修工单")
    public ResponseEntity<Boolean> completeRepair(
            @Parameter(description = "工单ID", required = true) @PathVariable @NotNull Long orderId,
            @Parameter(description = "维修结果", required = true) @RequestParam @NotNull String repairResult,
            @Parameter(description = "维修费用") @RequestParam(required = false) String repairCost,
            @Parameter(description = "工时") @RequestParam(required = false) String workHours,
            @Parameter(description = "完成备注") @RequestParam(required = false) String remark) {
        
        log.info("完成维修，工单ID：{}，维修结果：{}，维修费用：{}，工时：{}", orderId, repairResult, repairCost, workHours);
        
        boolean result = repairOrderWorkService.completeRepair(orderId, repairResult, repairCost, workHours, remark);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/{orderId}/rating")
    @Operation(summary = "提交客户评价", description = "客户对维修工单进行评价")
    public ResponseEntity<Boolean> submitCustomerRating(
            @Parameter(description = "工单ID", required = true) @PathVariable @NotNull Long orderId,
            @Parameter(description = "满意度评分", required = true) @RequestParam @NotNull Integer satisfaction,
            @Parameter(description = "客户评价") @RequestParam(required = false) String comment) {
        
        log.info("提交客户评价，工单ID：{}，满意度：{}，评价：{}", orderId, satisfaction, comment);
        
        boolean result = repairOrderWorkService.submitCustomerRating(orderId, satisfaction, comment);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/repairman/{repairmanId}")
    @Operation(summary = "查询维修人员工单", description = "查询指定维修人员的工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getRepairOrdersByRepairman(
            @Parameter(description = "维修人员ID", required = true) @PathVariable @NotNull Long repairmanId,
            @Parameter(description = "工单状态") @RequestParam(required = false) Integer status) {
        
        log.info("查询维修人员工单，维修人员ID：{}，状态：{}", repairmanId, status);
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        List<RepairOrderWorkVO> result = repairOrderWorkService.getRepairOrdersByRepairman(repairmanId, propertyCompanyId, status);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/urgent")
    @Operation(summary = "查询紧急工单", description = "查询紧急维修工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getUrgentRepairOrders() {
        
        log.info("查询紧急工单");
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        List<RepairOrderWorkVO> result = repairOrderWorkService.getUrgentRepairOrders(propertyCompanyId);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/timeout")
    @Operation(summary = "查询超时工单", description = "查询超时维修工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getTimeoutRepairOrders(
            @Parameter(description = "超时小时数", required = true) @RequestParam @NotNull Integer timeoutHours) {
        
        log.info("查询超时工单，超时小时数：{}", timeoutHours);
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        List<RepairOrderWorkVO> result = repairOrderWorkService.getTimeoutRepairOrders(propertyCompanyId, timeoutHours);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/pending-assign")
    @Operation(summary = "查询待分配工单", description = "查询待分配维修工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getPendingAssignRepairOrders() {
        
        log.info("查询待分配工单");
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        List<RepairOrderWorkVO> result = repairOrderWorkService.getPendingAssignRepairOrders(propertyCompanyId);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/in-progress")
    @Operation(summary = "查询进行中工单", description = "查询进行中维修工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getInProgressRepairOrders() {
        
        log.info("查询进行中工单");
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        List<RepairOrderWorkVO> result = repairOrderWorkService.getInProgressRepairOrders(propertyCompanyId);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/completed")
    @Operation(summary = "查询已完成工单", description = "查询已完成维修工单列表")
    public ResponseEntity<List<RepairOrderWorkVO>> getCompletedRepairOrders(
            @Parameter(description = "开始日期", required = true) @RequestParam @NotNull String startDate,
            @Parameter(description = "结束日期", required = true) @RequestParam @NotNull String endDate) {
        
        log.info("查询已完成工单，开始日期：{}，结束日期：{}", startDate, endDate);
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<RepairOrderWorkVO> result = repairOrderWorkService.getCompletedRepairOrders(propertyCompanyId, start, end);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "查询维修工单统计信息", description = "查询维修工单统计信息")
    public ResponseEntity<Map<String, Object>> getRepairOrderWorkStatistics(
            @Parameter(description = "开始日期", required = true) @RequestParam @NotNull String startDate,
            @Parameter(description = "结束日期", required = true) @RequestParam @NotNull String endDate) {
        
        log.info("查询维修工单统计信息，开始日期：{}，结束日期：{}", startDate, endDate);
        
        Long propertyCompanyId = SecurityUtils.getCurrentPropertyCompanyId();
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        Map<String, Object> result = repairOrderWorkService.getRepairOrderWorkStatistics(propertyCompanyId, start, end);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/sources")
    @Operation(summary = "获取工单来源列表", description = "获取工单来源列表")
    public ResponseEntity<List<Map<String, Object>>> getRepairOrderSourceList() {
        
        log.info("获取工单来源列表");
        
        List<Map<String, Object>> result = repairOrderWorkService.getRepairOrderSourceList();
        return ResponseEntity.ok(result);
    }

    @GetMapping("/categories")
    @Operation(summary = "获取工单分类列表", description = "获取工单分类列表")
    public ResponseEntity<List<Map<String, Object>>> getRepairOrderCategoryList() {
        
        log.info("获取工单分类列表");
        
        List<Map<String, Object>> result = repairOrderWorkService.getRepairOrderCategoryList();
        return ResponseEntity.ok(result);
    }

    @GetMapping("/notification-methods")
    @Operation(summary = "获取通知方式列表", description = "获取通知方式列表")
    public ResponseEntity<List<Map<String, Object>>> getNotificationMethodList() {
        
        log.info("获取通知方式列表");
        
        List<Map<String, Object>> result = repairOrderWorkService.getNotificationMethodList();
        return ResponseEntity.ok(result);
    }
}
